import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:url_launcher/url_launcher.dart';
import '../models/todo_item.dart';
import '../models/category.dart' as model;
import '../services/api_service.dart';
import '../services/local_cache_service.dart';
import 'todo_detail_page.dart';
import '../widgets/todo_list_widget.dart';
import '../widgets/todo_detail_widget.dart';
import '../widgets/category_tree_widget.dart';
import '../widgets/todo_filter_actions_widget.dart';

// 定义新建待办的Intent
class NewTodoIntent extends Intent {
  const NewTodoIntent();
}

class TodoListPage extends StatefulWidget {
  const TodoListPage({super.key});

  @override
  State<TodoListPage> createState() => _TodoListPageState();
}

class _TodoListPageState extends State<TodoListPage> with WidgetsBindingObserver {
  List<TodoItem> _todoList = [];
  List<model.Category> _categories = [];
  String? _selectedCategoryId;
  model.Category? _selectedCategory; // 选中的分类对象
  bool _isLoading = false;
  bool _isLoadingCategories = false;
  String? _errorMessage;
  TodoItem? _selectedTodo;
  bool _isCreateMode = false; // 是否为创建模式
  bool _showCompleted = false; // 是否显示已完成项（默认不显示）
  String? _todoFilter = 'favorite'; // 待办筛选状态：'all', 'uncategorized', 'favorite'（默认显示关注列表）

  final TextEditingController _contentController = TextEditingController();
  final FocusNode _contentFocusNode = FocusNode();

  Timer? _localSaveTimer; // 本地保存定时器
  static const Duration _localSaveDuration = Duration(milliseconds: 300); // 本地保存延迟300ms

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _loadCategoryList();
    _restoreLastSelectedCategory();
    _restoreShowCompletedState();

    // 监听输入变化，触发自动保存
    _contentController.addListener(_onTextChanged);

    // 监听焦点变化
    _contentFocusNode.addListener(_onFocusChanged);

    // 启动时恢复本地草稿
    _restoreLocalDrafts();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _localSaveTimer?.cancel();
    _contentController.removeListener(_onTextChanged);
    _contentFocusNode.removeListener(_onFocusChanged);
    _contentController.dispose();
    _contentFocusNode.dispose();
    super.dispose();
  }

  // 应用生命周期变化
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.paused) {
      // 应用进入后台，立即同步到服务器
      _syncToServer();
    }
  }

  // 焦点变化监听
  void _onFocusChanged() {
    if (!_contentFocusNode.hasFocus) {
      // 失去焦点，立即同步到服务器
      _syncToServer();
    }
  }

  // 递归查找分类
  model.Category? _findCategoryById(List<model.Category> categories, String categoryId) {
    for (final category in categories) {
      if (category.id == categoryId) {
        return category;
      }
      if (category.children.isNotEmpty) {
        final found = _findCategoryById(category.children, categoryId);
        if (found != null) {
          return found;
        }
      }
    }
    return null;
  }

  // 恢复上次选择的分类
  Future<void> _restoreLastSelectedCategory() async {
    // 启动时默认显示关注列表，不恢复上次的分类
    // 加载关注列表
    _loadTodoList();
  }

  // 恢复"显示已完成"状态
  Future<void> _restoreShowCompletedState() async {
    final showCompleted = await LocalCacheService.getShowCompleted();
    setState(() {
      _showCompleted = showCompleted;
    });
  }


  // 恢复本地草稿
  Future<void> _restoreLocalDrafts() async {
    final drafts = await LocalCacheService.getAllDrafts();
    if (drafts.isEmpty) return;
    // TODO: 这里可以提示用户有未同步的草稿
  }

  // 同步到服务器
  Future<void> _syncToServer() async {
    if (_selectedTodo == null) return;

    final content = _contentController.text.trim();
    if (content.isEmpty) return;

    if (_isCreateMode) {
      await _autoCreate();
    } else {
      await _autoSave();
    }
  }

  void _onTextChanged() {
    final content = _contentController.text.trim();

    // 创建模式：检查是否有内容
    if (_isCreateMode) {
      if (content.isEmpty) {
        _localSaveTimer?.cancel();
        return;
      }

      // 只保存到本地（延迟300ms）
      _localSaveTimer?.cancel();
      _localSaveTimer = Timer(_localSaveDuration, () {
        if (_selectedTodo != null) {
          LocalCacheService.saveDraft(_selectedTodo!.id, content);
        }
      });
      return;
    }

    // 编辑模式：检查是否有改变
    if (_selectedTodo == null) return;

    final hasChanges = content != (_selectedTodo!.content ?? '');

    if (!hasChanges) {
      _localSaveTimer?.cancel();
      return;
    }

    // 只保存到本地（延迟300ms）
    _localSaveTimer?.cancel();
    _localSaveTimer = Timer(_localSaveDuration, () {
      LocalCacheService.saveDraft(_selectedTodo!.id, content);
    });
  }

  Future<void> _loadCategoryList() async {
    setState(() {
      _isLoadingCategories = true;
    });

    try {
      final categories = await ApiService.getCategoryList();
      setState(() {
        _categories = categories;
        _isLoadingCategories = false;
      });
    } catch (e) {
      setState(() {
        _isLoadingCategories = false;
      });
      // 静默失败
    }
  }

  Future<void> _loadTodoList({String? categoryId, bool silent = false}) async {
    // 非静默模式才显示加载状态
    if (!silent) {
      setState(() {
        _isLoading = true;
        _errorMessage = null;
      });
    }

    try {
      final todoList = await ApiService.getTodoList(
        categoryId: categoryId,
        isCompleted: _showCompleted ? null : false, // true=显示所有(null), false=只显示未完成
        isFavorite: _todoFilter == 'favorite' ? true : null, // 关注筛选
      );
      setState(() {
        _todoList = todoList;
        _isLoading = false;
        // 切换分类时清空选中项，或选中第一项
        if (_todoList.isNotEmpty) {
          _selectedTodo = _todoList.first;
          _contentController.text = _selectedTodo!.content ?? '';
        } else {
          _selectedTodo = null;
          _contentController.clear();
        }
      });
    } catch (e) {
      setState(() {
        _errorMessage = e.toString();
        _isLoading = false;
      });
    }
  }

  void _onCategorySelected(String? categoryId) {
    setState(() {
      _selectedCategoryId = categoryId;
      _isCreateMode = false;
      // 更新选中的分类对象
      if (categoryId != null && categoryId != '-1') {
        _selectedCategory = _findCategoryById(_categories, categoryId);
      } else {
        _selectedCategory = null;
      }
      // 清空筛选状态（切换分类时取消关注筛选）
      _todoFilter = null;
    });
    // 保存最后选择的分类
    LocalCacheService.saveLastSelectedCategory(categoryId);
    // 静默刷新待办列表（不显示加载框）
    _loadTodoList(categoryId: categoryId, silent: true);
  }

  void _onTodoItemTap(TodoItem todo) async {
    // iOS: 导航到详情页
    if (Platform.isIOS) {
      await Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => TodoDetailPage(
            todo: todo,
            categoryId: _selectedCategoryId,
            onUpdate: (updatedTodo) {
              // 更新列表中的数据
              setState(() {
                final index = _todoList.indexWhere((t) => t.id == updatedTodo.id);
                if (index != -1) {
                  _todoList[index] = updatedTodo;
                }
              });
            },
            onInsert: (newTodo) {
              // 插入新创建的待办到列表开头
              setState(() {
                _todoList.insert(0, newTodo);
              });
            },
          ),
        ),
      );
      // 返回后静默刷新列表（如果在详情页删除了待办）
      _loadTodoList(categoryId: _selectedCategoryId, silent: true);
      return;
    }

    // macOS: 切换前检查是否有空的临时项需要删除
    if (_isCreateMode && _selectedTodo != null) {
      final content = _contentController.text.trim();
      if (content.isEmpty) {
        // 删除空的临时项
        setState(() {
          _todoList.removeWhere((t) => t.id.startsWith('temp_'));
        });
      }
    }

    // macOS: 在右侧显示详情
    setState(() {
      _isCreateMode = false;
      _selectedTodo = todo;
      // 只显示 content
      _contentController.text = todo.content ?? '';
    });
  }

  void _startCreateMode() {
    // iOS: 导航到详情页（创建模式）
    if (Platform.isIOS) {
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => TodoDetailPage(
            todo: null, // null表示创建新待办
            categoryId: _selectedCategoryId,
            onUpdate: (updatedTodo) {
              // 创建模式不会用到onUpdate
            },
            onInsert: (newTodo) {
              // 插入新创建的待办到列表开头
              setState(() {
                _todoList.insert(0, newTodo);
              });
            },
          ),
        ),
      );
      return;
    }

    // macOS: 创建临时待办项并插入列表顶部
    final tempTodo = TodoItem(
      id: 'temp_${DateTime.now().millisecondsSinceEpoch}',
      content: '',
    );

    setState(() {
      _todoList.insert(0, tempTodo);
      _isCreateMode = true;
      _selectedTodo = tempTodo;
      _contentController.clear();
    });
  }

  // 选择上一项
  void _selectPreviousTodo() {
    if (_todoList.isEmpty || _selectedTodo == null) return;

    final currentIndex = _todoList.indexWhere((t) => t.id == _selectedTodo!.id);
    if (currentIndex <= 0) return; // 已经是第一项

    final previousTodo = _todoList[currentIndex - 1];
    setState(() {
      _isCreateMode = false;
      _selectedTodo = previousTodo;
      _contentController.text = previousTodo.content ?? '';
    });
  }

  // 选择下一项
  void _selectNextTodo() {
    if (_todoList.isEmpty || _selectedTodo == null) return;

    final currentIndex = _todoList.indexWhere((t) => t.id == _selectedTodo!.id);
    if (currentIndex == -1 || currentIndex >= _todoList.length - 1) return; // 已经是最后一项

    final nextTodo = _todoList[currentIndex + 1];
    setState(() {
      _isCreateMode = false;
      _selectedTodo = nextTodo;
      _contentController.text = nextTodo.content ?? '';
    });
  }

  Future<void> _autoCreate() async {
    if (!_isCreateMode) return;

    final content = _contentController.text.trim();
    if (content.isEmpty) return;

    // 使用第一行作为标题
    final lines = content.split('\n');
    final title = lines.first.trim();
    if (title.isEmpty) return;

    final tempId = _selectedTodo?.id;

    try {
      final newTodo = await ApiService.createTodo(
        title,
        content,
        categoryId: _selectedCategoryId,
      );

      if (mounted) {
        setState(() {
          // 查找并替换临时项
          final tempIndex = _todoList.indexWhere((t) => t.id.startsWith('temp_'));
          if (tempIndex != -1) {
            _todoList[tempIndex] = newTodo;
          } else {
            // 如果找不到临时项，添加到列表开头
            _todoList.insert(0, newTodo);
          }
          // 选中新创建的项
          _selectedTodo = newTodo;
          _isCreateMode = false;
        });

        // 同步成功，删除本地缓存
        if (tempId != null) {
          await LocalCacheService.deleteDraft(tempId);
        }
      }
    } catch (e) {
      // 静默失败
    }
  }

  Future<void> _autoSave() async {
    if (_selectedTodo == null) return;

    final content = _contentController.text.trim();
    if (content.isEmpty) return;

    // 使用第一行作为标题
    final lines = content.split('\n');
    final title = lines.first.trim();
    if (title.isEmpty) return;

    final todoId = _selectedTodo!.id;

    try {
      final updatedTodo = await ApiService.updateTodo(
        todoId,
        title,
        content,
      );

      if (mounted) {
        setState(() {
          // 更新列表中的数据
          final index = _todoList.indexWhere((t) => t.id == updatedTodo.id);
          if (index != -1) {
            _todoList[index] = updatedTodo;
          }
          // 只有当前选中的待办仍然是刚保存的待办时,才更新选中项
          // 这样可以避免用户切换到其他待办后又被跳回来
          if (_selectedTodo?.id == updatedTodo.id) {
            _selectedTodo = updatedTodo;
          }
        });

        // 同步成功，删除本地缓存
        await LocalCacheService.deleteDraft(todoId);
      }
    } catch (e) {
      // 静默失败
    }
  }

  Future<void> _onToggleTop(bool isTop) async {
    if (_selectedTodo == null) return;

    final todoId = _selectedTodo!.id;

    try {
      final updatedTodo = await ApiService.toggleTop(todoId, isTop);

      if (mounted) {
        setState(() {
          // 更新列表中的数据
          final index = _todoList.indexWhere((t) => t.id == updatedTodo.id);
          if (index != -1) {
            _todoList[index] = updatedTodo;
          }
          _selectedTodo = updatedTodo;
        });

        // 静默刷新列表以更新排序（置顶项应该排在前面）
        await _loadTodoList(categoryId: _selectedCategoryId, silent: true);

        // 刷新后重新选中该项
        if (mounted) {
          setState(() {
            final refreshedTodo = _todoList.firstWhere(
              (t) => t.id == todoId,
              orElse: () => _todoList.isNotEmpty ? _todoList.first : updatedTodo,
            );
            _selectedTodo = refreshedTodo;
            _contentController.text = refreshedTodo.content ?? '';
          });
        }
      }
    } catch (e) {
      // 显示错误提示
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('操作失败: $e')),
        );
      }
    }
  }

  Future<void> _onFavoriteChanged(bool isFavorite) async {
    if (_selectedTodo == null) return;

    final todoId = _selectedTodo!.id;

    try {
      final updatedTodo = await ApiService.updateFavorite(todoId, isFavorite);

      if (mounted) {
        setState(() {
          // 更新列表中的数据
          final index = _todoList.indexWhere((t) => t.id == updatedTodo.id);
          if (index != -1) {
            _todoList[index] = updatedTodo;
          }
          _selectedTodo = updatedTodo;
        });
      }
    } catch (e) {
      // 显示错误提示
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('更新关注状态失败: $e')),
        );
      }
    }
  }

  Future<void> _onDelete() async {
    if (_selectedTodo == null) return;

    // 提取第一行作为显示标题
    String displayTitle = '无标题';
    if (_selectedTodo!.content != null && _selectedTodo!.content!.isNotEmpty) {
      final lines = _selectedTodo!.content!.split('\n');
      final firstLine = lines.first.trim();
      if (firstLine.isNotEmpty) {
        displayTitle = firstLine;
      }
    }

    // 显示确认对话框
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除待办"$displayTitle"吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            style: TextButton.styleFrom(foregroundColor: Colors.red),
            child: const Text('删除'),
          ),
        ],
      ),
    );

    if (confirmed != true) return;

    final todoId = _selectedTodo!.id;

    try {
      await ApiService.deleteTodo(todoId);

      if (mounted) {
        setState(() {
          // 从列表中删除
          _todoList.removeWhere((t) => t.id == todoId);

          // 选中下一项或清空
          if (_todoList.isNotEmpty) {
            _selectedTodo = _todoList.first;
            _contentController.text = _selectedTodo!.content ?? '';
          } else {
            _selectedTodo = null;
            _contentController.clear();
          }
        });

        // 删除本地缓存
        await LocalCacheService.deleteDraft(todoId);
      }
    } catch (e) {
      // 显示错误提示
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('删除失败: $e')),
        );
      }
    }
  }

  Future<void> _onTodoDrop(String todoId, String categoryId) async {
    try {
      final updatedTodo = await ApiService.updateCategory(todoId, categoryId);

      if (mounted) {
        // 切换到目标分类
        setState(() {
          _selectedCategoryId = categoryId;
          _isCreateMode = false;
          // 更新选中的分类对象
          _selectedCategory = _findCategoryById(_categories, categoryId);
        });

        // 保存最后选择的分类
        LocalCacheService.saveLastSelectedCategory(categoryId);

        // 刷新目标分类的待办列表，并选中被拖拽的待办项
        await _loadTodoList(categoryId: categoryId, silent: false);

        // 在列表加载完成后，选中被拖拽的待办项
        if (mounted) {
          setState(() {
            final draggedTodo = _todoList.firstWhere(
              (t) => t.id == todoId,
              orElse: () => _todoList.isNotEmpty ? _todoList.first : updatedTodo,
            );
            _selectedTodo = draggedTodo;
            _contentController.text = draggedTodo.content ?? '';
          });
        }
      }
    } catch (e) {
      // 显示错误提示
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('移动失败: $e')),
        );
      }
    }
  }

  // 分类拖拽(旧的,改变父级)
  Future<void> _onCategoryDrop(String categoryId, String targetCategoryId) async {
    try {
      // 调用API更新分类的父级
      await ApiService.updateCategoryParent(
        categoryId: categoryId,
        parentId: targetCategoryId,
      );

      // 刷新分类列表
      await _loadCategoryList();

      // 显示成功提示
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('分类移动成功')),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('移动失败: $e')),
        );
      }
    }
  }

  // 分类拖拽排序(新的,支持前/后/里)
  Future<void> _onCategoryDrag(String categoryId, String targetId, String dropType) async {
    try {
      // 调用API拖拽分类
      await ApiService.dragCategory(
        categoryId: categoryId,
        targetId: targetId,
        dropType: dropType,
      );

      // 刷新分类列表
      await _loadCategoryList();
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('拖拽失败: $e')),
        );
      }
    }
  }

  // 新增分类
  Future<void> _onAddCategory() async {
    final nameController = TextEditingController();
    String? categoryName;

    final result = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('新增分类'),
        content: TextField(
          controller: nameController,
          autofocus: true,
          decoration: const InputDecoration(
            hintText: '请输入分类名称',
            border: OutlineInputBorder(),
          ),
          onSubmitted: (_) {
            // 回车直接提交
            if (nameController.text.trim().isNotEmpty) {
              Navigator.pop(context, true);
            }
          },
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              if (nameController.text.trim().isEmpty) {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('分类名称不能为空')),
                );
                return;
              }
              Navigator.pop(context, true);
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );

    // 保存文本内容
    categoryName = nameController.text.trim();
    // 立即释放 controller
    nameController.dispose();

    if (result == true && categoryName.isNotEmpty) {
      try {
        // 调用API创建分类
        await ApiService.createCategory(
          name: categoryName,
          parentId: null, // 顶级分类，parentId为null
        );

        // 刷新分类列表
        await _loadCategoryList();

        // 显示成功提示
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('分类创建成功')),
          );
        }
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('创建失败: $e')),
          );
        }
      }
    }
  }

  // 待办筛选切换
  void _onTodoFilterChanged(String? filter) {
    setState(() {
      _todoFilter = filter;
      // 清空分类选择
      _selectedCategoryId = null;
      _selectedCategory = null;
    });

    // 根据筛选类型加载数据
    if (filter == 'uncategorized') {
      // 未分类待办
      _loadTodoList(categoryId: '-1', silent: true);
    } else if (filter == 'favorite') {
      // 关注待办
      _loadTodoList(silent: true);
    } else {
      // 全部待办
      _loadTodoList(categoryId: null, silent: true);
    }
  }

  // 切换显示已完成
  void _onShowCompletedChanged(bool show) {
    setState(() {
      _showCompleted = show;
    });
    // 保存状态到本地
    LocalCacheService.saveShowCompleted(_showCompleted);
    // 刷新列表
    _loadTodoList(categoryId: _selectedCategoryId, silent: true);
  }

  // 删除分类
  Future<void> _onDeleteCategory() async {
    if (_selectedCategory == null) return;

    // 显示确认对话框
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除分类"${_selectedCategory!.name}"吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            style: TextButton.styleFrom(foregroundColor: Colors.red),
            child: const Text('删除'),
          ),
        ],
      ),
    );

    if (confirmed != true) return;

    try {
      // 调用API删除分类
      await ApiService.deleteCategory(_selectedCategory!.id);

      // 刷新分类列表
      await _loadCategoryList();

      // 清空选中的分类
      setState(() {
        _selectedCategoryId = null;
        _selectedCategory = null;
      });

      // 刷新待办列表
      await _loadTodoList(categoryId: null, silent: true);

      // 显示成功提示
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('分类删除成功')),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('删除失败: $e')),
        );
      }
    }
  }

  // 修改分类
  Future<void> _onEditCategory() async {
    if (_selectedCategory == null) return;

    final nameController = TextEditingController(text: _selectedCategory!.name);
    String? categoryName;

    final result = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('修改分类'),
        content: TextField(
          controller: nameController,
          autofocus: true,
          decoration: const InputDecoration(
            hintText: '请输入分类名称',
            border: OutlineInputBorder(),
          ),
          onSubmitted: (_) {
            // 回车直接提交
            if (nameController.text.trim().isNotEmpty) {
              Navigator.pop(context, true);
            }
          },
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              if (nameController.text.trim().isEmpty) {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('分类名称不能为空')),
                );
                return;
              }
              Navigator.pop(context, true);
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );

    // 保存文本内容
    categoryName = nameController.text.trim();
    // 立即释放 controller
    nameController.dispose();

    if (result == true && categoryName.isNotEmpty) {
      try {
        // 调用API更新分类名称
        await ApiService.updateCategoryName(
          categoryId: _selectedCategory!.id,
          name: categoryName,
        );

        // 刷新分类列表
        await _loadCategoryList();

        // 更新本地选中的分类对象
        if (mounted) {
          setState(() {
            _selectedCategory = _findCategoryById(_categories, _selectedCategory!.id);
          });

          // 显示成功提示
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('分类修改成功')),
          );
        }
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('修改失败: $e')),
          );
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Shortcuts(
      shortcuts: <LogicalKeySet, Intent>{
        LogicalKeySet(LogicalKeyboardKey.meta, LogicalKeyboardKey.keyN): const NewTodoIntent(),
      },
      child: Actions(
        actions: <Type, Action<Intent>>{
          NewTodoIntent: CallbackAction<NewTodoIntent>(
            onInvoke: (NewTodoIntent intent) {
              _startCreateMode();
              return null;
            },
          ),
        },
        child: Focus(
          autofocus: true,
          onKeyEvent: (FocusNode node, KeyEvent event) {
            // 只处理按键按下事件
            if (event is! KeyDownEvent) {
              return KeyEventResult.ignored;
            }

            // 如果焦点在编辑框内，不处理上下键（让TextField处理）
            if (_contentFocusNode.hasFocus) {
              return KeyEventResult.ignored;
            }

            // 处理上下键切换待办
            if (event.logicalKey == LogicalKeyboardKey.arrowUp) {
              _selectPreviousTodo();
              return KeyEventResult.handled;
            } else if (event.logicalKey == LogicalKeyboardKey.arrowDown) {
              _selectNextTodo();
              return KeyEventResult.handled;
            }

            return KeyEventResult.ignored;
          },
          child: Scaffold(
            // 只有iOS显示AppBar
            appBar: Platform.isIOS
                ? AppBar(
                    backgroundColor: Theme.of(context).colorScheme.inversePrimary,
                    // iOS: 添加展开侧边栏按钮
                    leading: Builder(
                      builder: (BuildContext context) {
                        return IconButton(
                          icon: const Icon(Icons.menu),
                          onPressed: () {
                            Scaffold.of(context).openDrawer();
                          },
                          tooltip: '分类',
                        );
                      },
                    ),
                    title: const Text('待办计划'),
                    actions: [
                      IconButton(
                        icon: const Icon(Icons.add),
                        onPressed: _startCreateMode,
                        tooltip: '新建 (⌘N)',
                      ),
                      IconButton(
                        icon: const Icon(Icons.refresh),
                        onPressed: _loadTodoList,
                        tooltip: '刷新',
                      ),
                    ],
                  )
                : null, // macOS 不显示 AppBar
            // iOS: 添加侧边栏
            drawer: Platform.isIOS ? _buildDrawer() : null,
            body: _buildBody(),
          ),
        ),
      ),
    );
  }

  /// 处理分类描述中的链接点击
  Future<void> _handleCategoryDescriptionLinkTap(String text, String? href, String title) async {
    if (href == null) return;

    final uri = Uri.tryParse(href);
    if (uri == null) return;

    try {
      if (await canLaunchUrl(uri)) {
        await launchUrl(uri, mode: LaunchMode.externalApplication);
      }
    } catch (e) {
      // 静默失败
    }
  }

  // 分类操作栏 + 描述展示区域
  Widget _buildCategoryDescription() {
    final hasCategory = _selectedCategory != null;
    final hasDescription = _selectedCategory?.description != null &&
                          _selectedCategory!.description!.isNotEmpty;

    // 如果没有选中分类，不显示此区域
    if (!hasCategory) {
      return const SizedBox.shrink();
    }

    return Column(
      children: [
        // 分类描述区域（如果有描述）
        if (hasDescription)
          Container(
            height: 120, // 固定高度
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            decoration: BoxDecoration(
              color: Colors.grey[50],
              border: Border(
                bottom: BorderSide(color: Colors.grey[300]!),
              ),
            ),
            child: MarkdownBody(
              data: _selectedCategory!.description!,
              selectable: true,
              onTapLink: _handleCategoryDescriptionLinkTap,
              styleSheet: MarkdownStyleSheet(
                p: TextStyle(
                  fontSize: 13,
                  color: Colors.grey[700],
                  height: 1.5,
                ),
                a: TextStyle(
                  fontSize: 13,
                  color: Colors.blue[700],
                  decoration: TextDecoration.underline,
                ),
                code: TextStyle(
                  fontSize: 12,
                  backgroundColor: Colors.grey[200],
                  color: Colors.grey[800],
                ),
                strong: TextStyle(
                  fontSize: 13,
                  color: Colors.grey[800],
                  fontWeight: FontWeight.bold,
                ),
                em: TextStyle(
                  fontSize: 13,
                  color: Colors.grey[700],
                  fontStyle: FontStyle.italic,
                ),
                listBullet: TextStyle(
                  fontSize: 13,
                  color: Colors.grey[700],
                ),
              ),
            ),
          ),
      ],
    );
  }

  // iOS侧边栏
  Widget _buildDrawer() {
    return Drawer(
      child: SafeArea(
        child: Column(
          children: [
            // 侧边栏头部
            Container(
              padding: const EdgeInsets.all(16),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text(
                    '分类',
                    style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  IconButton(
                    icon: const Icon(Icons.close),
                    onPressed: () {
                      Navigator.pop(context);
                    },
                  ),
                ],
              ),
            ),
            const Divider(height: 1),
            // 分类树
            Expanded(
              child: _isLoadingCategories
                  ? const Center(child: CircularProgressIndicator())
                  : CategoryTreeWidget(
                      key: const ValueKey('category_tree_drawer'),
                      categories: _categories,
                      selectedCategoryId: _selectedCategoryId,
                      onCategorySelected: (categoryId) {
                        // 关闭侧边栏
                        Navigator.pop(context);
                        // 选择分类
                        _onCategorySelected(categoryId);
                      },
                      onTodoDrop: _onTodoDrop,
                      onAddCategory: _onAddCategory,
                      onEditCategory: _onEditCategory,
                      onDeleteCategory: _onDeleteCategory,
                      onRefreshCategory: _loadCategoryList,
                      onCategoryDrop: _onCategoryDrop,
                      onCategoryDrag: _onCategoryDrag,
                    ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBody() {
    // iOS: 单列布局，可以整体替换
    if (Platform.isIOS) {
      if (_isLoading) {
        return const Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              CircularProgressIndicator(),
              SizedBox(height: 16),
              Text('加载中...'),
            ],
          ),
        );
      }

      if (_errorMessage != null) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.error_outline,
                size: 64,
                color: Colors.red[300],
              ),
              const SizedBox(height: 16),
              Text(
                _errorMessage!,
                style: const TextStyle(color: Colors.red),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 16),
              ElevatedButton(
                onPressed: _loadTodoList,
                child: const Text('重试'),
              ),
            ],
          ),
        );
      }

      if (_todoList.isEmpty) {
        return Column(
          children: [
            _buildCategoryDescription(),
            // 显示/隐藏已完成复选框
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              decoration: BoxDecoration(
                border: Border(
                  bottom: BorderSide(color: Colors.grey[300]!),
                ),
              ),
              child: Row(
                children: [
                  Checkbox(
                    value: _showCompleted,
                    onChanged: (bool? value) {
                      setState(() {
                        _showCompleted = value ?? true;
                      });
                      // 保存状态到本地
                      LocalCacheService.saveShowCompleted(_showCompleted);
                      _loadTodoList(categoryId: _selectedCategoryId, silent: true);
                    },
                    materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                    visualDensity: const VisualDensity(horizontal: -4, vertical: -4),
                  ),
                  const SizedBox(width: 8),
                  Text(
                    '显示已完成',
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.grey[700],
                    ),
                  ),
                ],
              ),
            ),
            const Expanded(
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.inbox_outlined,
                      size: 64,
                      color: Colors.grey,
                    ),
                    SizedBox(height: 16),
                    Text(
                      '暂无待办事项',
                      style: TextStyle(color: Colors.grey),
                    ),
                  ],
                ),
              ),
            ),
          ],
        );
      }

      return Column(
        children: [
          _buildCategoryDescription(),
          // 显示/隐藏已完成复选框
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(color: Colors.grey[300]!),
              ),
            ),
            child: Row(
              children: [
                Checkbox(
                  value: _showCompleted,
                  onChanged: (bool? value) {
                    setState(() {
                      _showCompleted = value ?? true;
                    });
                    // 保存状态到本地
                    LocalCacheService.saveShowCompleted(_showCompleted);
                    _loadTodoList(categoryId: _selectedCategoryId, silent: true);
                  },
                  materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                  visualDensity: const VisualDensity(horizontal: -4, vertical: -4),
                ),
                const SizedBox(width: 8),
                Text(
                  '显示已完成',
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[700],
                  ),
                ),
              ],
            ),
          ),
          Expanded(
            child: TodoListWidget(
              todoList: _todoList,
              selectedTodo: _selectedTodo,
              onTodoItemTap: _onTodoItemTap,
              onCategoryTap: _onCategorySelected,
            ),
          ),
        ],
      );
    }

    // macOS: 三列布局（分类树 | 待办列表 | 详情）
    return Row(
      children: [
        // 左侧：分类树
        SizedBox(
          width: 220,
          child: CategoryTreeWidget(
            key: const ValueKey('category_tree'),
            categories: _categories,
            selectedCategoryId: _selectedCategoryId,
            onCategorySelected: _onCategorySelected,
            onTodoDrop: _onTodoDrop,
            onAddCategory: _onAddCategory,
            onEditCategory: _onEditCategory,
            onDeleteCategory: _onDeleteCategory,
            onRefreshCategory: _loadCategoryList,
            onCategoryDrop: _onCategoryDrop,
            onCategoryDrag: _onCategoryDrag,
          ),
        ),
        // 分割线
        Container(
          width: 1,
          color: Colors.grey[300],
        ),
        // 中间：待办列表
        Container(
          width: 320,
          color: Colors.white,
          child: _isLoading
              ? const Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      CircularProgressIndicator(),
                      SizedBox(height: 16),
                      Text('加载中...'),
                    ],
                  ),
                )
              : _errorMessage != null
                  ? Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(
                            Icons.error_outline,
                            size: 64,
                            color: Colors.red[300],
                          ),
                          const SizedBox(height: 16),
                          Text(
                            _errorMessage!,
                            style: const TextStyle(color: Colors.red),
                            textAlign: TextAlign.center,
                          ),
                          const SizedBox(height: 16),
                          ElevatedButton(
                            onPressed: _loadTodoList,
                            child: const Text('重试'),
                          ),
                        ],
                      ),
                    )
                  : _todoList.isEmpty
                      ? Column(
                          children: [
                            // 【待办列表筛选操作区域】
                            TodoFilterActionsWidget(
                              selectedFilter: _todoFilter,
                              showCompleted: _showCompleted,
                              onFilterChanged: _onTodoFilterChanged,
                              onShowCompletedChanged: _onShowCompletedChanged,
                            ),
                            _buildCategoryDescription(),
                            const Expanded(
                              child: Center(
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Icon(
                                      Icons.inbox_outlined,
                                      size: 64,
                                      color: Colors.grey,
                                    ),
                                    SizedBox(height: 16),
                                    Text(
                                      '暂无待办事项',
                                      style: TextStyle(color: Colors.grey),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        )
                      : Column(
                          children: [
                            // 【待办列表筛选操作区域】
                            TodoFilterActionsWidget(
                              selectedFilter: _todoFilter,
                              showCompleted: _showCompleted,
                              onFilterChanged: _onTodoFilterChanged,
                              onShowCompletedChanged: _onShowCompletedChanged,
                            ),
                            _buildCategoryDescription(),
                            Expanded(
                              child: TodoListWidget(
                                todoList: _todoList,
                                selectedTodo: _selectedTodo,
                                onTodoItemTap: _onTodoItemTap,
                                onCategoryTap: _onCategorySelected,
                              ),
                            ),
                          ],
                        ),
        ),
        // 分割线
        Container(
          width: 1,
          color: Colors.grey[300],
        ),
        // 右侧：详情
        Expanded(
          child: Container(
            color: Colors.white,
            child: TodoDetailWidget(
              selectedTodo: _selectedTodo,
              isCreateMode: _isCreateMode,
              contentController: _contentController,
              focusNode: _contentFocusNode,
              onToggleTop: _onToggleTop,
              onDelete: _onDelete,
              onAdd: _startCreateMode,
              onRefresh: _loadTodoList,
              onContentChanged: (String newContent) {
                // 更新 controller 文本
                _contentController.text = newContent;
                // 直接触发同步到服务器（不依赖监听器）
                _syncToServer();
              },
              onFavoriteChanged: _onFavoriteChanged,
            ),
          ),
        ),
      ],
    );
  }
}
